package com.action;

import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.beans.Manufacturer;
import com.beans.Product;
import com.hibernate.HibernateUtil;
import com.opensymphony.xwork2.ActionSupport;


public class ProductListAction extends ActionSupport {
	
	private static final long serialVersionUID = 1L;
	private List<Product> ProductList;
	private Manufacturer provider;
	
	@SuppressWarnings("unchecked")
	public String performList() {
		Session session = HibernateUtil.getInstance().openSession();
		Transaction transaction = null;
		String ManuId = ServletActionContext.getRequest().getParameter("SelectedManuId");
		if(ManuId==null){
			ManuId=(String)ServletActionContext.getRequest().getSession().getAttribute("SelectedManuId");
		}
		
		//this is for the case where the View Product function is used in the search-result page, begin:
		String returntosearch=ServletActionContext.getRequest().getParameter("returntosearch");
		if(returntosearch!=null){
			ServletActionContext.getRequest().setAttribute("returntosearch", "true");
		}
		//end
		
		
		try {
			transaction = session.beginTransaction();
			provider = (Manufacturer) session.get(Manufacturer.class, Integer.parseInt(ManuId));
			Criteria criteria = session.createCriteria(Product.class);
		
			
			ProductList = criteria.add(Restrictions.eq("manufacturer",provider)).list();
			
			
		
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

		return SUCCESS;
	}
	
	public List<Product> getProductList() {
		return ProductList;
	}
	public void setProductList(List<Product> productList) {
		ProductList = productList;
	}

	public Manufacturer getProvider() {
		return provider;
	}

	public void setProvider(Manufacturer provider) {
		this.provider = provider;
	}

}
